package com.zoweunion.mechanic.plugins.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.zoweunion.mechanic.config.JpushConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * java后台极光推送方式二：使用Java SDK
 */
@SuppressWarnings("unused")
@Component
public class JiguangPush {

    private static final Logger log = LoggerFactory.getLogger(JiguangPush.class);

    @Autowired
    private JpushConfig jpushConfig;


    /**
     * 极光推送
     */
    public PushResult jiguangPush(String alias, String msg) {
        return this.jiguangPush(alias, msg, null);
    }

    /**
     * 极光推送
     */
    public PushResult jiguangPush(String alias, String msg, String title) {
        return this.jiguangPush(alias, msg, title, (Map<String, String>) null);
    }

    /**
     * 极光推送
     */
    public PushResult jiguangPush(String alias, String msg, String key, String value) {
        return jiguangPush(alias, msg, null, key, value);
    }

    /**
     * 极光推送
     */
    public PushResult jiguangPush(String alias, String msg, String title, String key, String value) {
        if (StringUtils.isBlank(key)) {
            return this.jiguangPush(alias, msg, title, (Map<String, String>) null);
        }
        Map<String, String> extraParams = new HashMap<>(2);
        extraParams.put(key, value);
        return this.jiguangPush(alias, msg, title, extraParams);
    }

    /**
     * 极光推送
     */
    public PushResult jiguangPush(String alias, String msg, String title, Map<String, String> extraParams) {
        log.debug("对别名" + alias + "的用户推送信息");
        PushResult result = push(alias, msg, title, extraParams);
        if (result != null && result.isResultOK()) {
            log.info("针对别名" + alias + "的信息推送成功！");
        } else {
            log.info("针对别名" + alias + "的信息推送失败！");
        }
        return result;
    }


    /**
     * 极光推送 跳转前端路径
     */
    public PushResult jiguangPushAll(String msg, String title) {
        return this.jiguangPushAll(msg, title, null);
    }

    /**
     * 极光推送 跳转前端路径
     */
    public PushResult jiguangPushAll(String msg, String title, String key, String value) {
        if (StringUtils.isBlank(key)) {
            return this.jiguangPushAll(msg, title,  null);
        }
        Map<String, String> extraParams = new HashMap<>(2);
        extraParams.put(key, value);
        return this.jiguangPushAll(msg, title, extraParams);
    }

    /**
     * 极光推送
     */
    public PushResult jiguangPushAll(String msg, String title, Map<String, String> extraParams) {
        log.debug("对所有用户推送信息");
        PushResult result = pushAll(msg, title, extraParams);
        if (result != null && result.isResultOK()) {
            log.info("对所有用户的信息推送成功！");
        } else {
            log.info("对所有用户的信息推送失败！");
        }
        return result;
    }

    /**
     * 极光推送方法(采用java SDK)
     *
     * @param alias
     * @param alert
     * @return PushResult
     */
    private PushResult push(String alias, String alert, String title, Map<String, String> extraParams) {
        PushPayload payload = buildPushObject_android_ios_alias_alert(alias, alert, title, extraParams);
        return this.sendPush(payload);
    }
    /**
     * 极光推送方法(采用java SDK)
     *
     * @param alert
     * @param title
     * @param extraParams
     * @return PushResult
     */
    private PushResult pushAll(String alert, String title, Map<String, String> extraParams) {
        PushPayload payload = buildPushObject_android_ios_all_alert(alert, title, extraParams);
        return this.sendPush(payload);
    }

    /**
     * 极光推送方法(采用java SDK)
     * 含title
     *
     * @param alias
     * @param alert
     * @return PushResult
     */
    private PushResult sendPush(String alias, String alert, String title, String key, String value) {
        Map<String, String> extraParams = new HashMap<>(3);
        extraParams.put(key, value);
        PushPayload payload = buildPushObject_android_ios_alias_alert(alias, alert, title, extraParams);
        return this.sendPush(payload);
    }
    /**
     * 极光推送方法(采用java SDK)
     * 含title
     *
     * @param alert
     * @param title
     * @param key
     * @param value
     * @return PushResult
     */
    private PushResult sendPushAll(String alert, String title, String key, String value) {
        Map<String, String> extraParams = new HashMap<>(3);
        extraParams.put(key, value);
        PushPayload payload = buildPushObject_android_ios_all_alert(alert, title, extraParams);
        return this.sendPush(payload);
    }

    private PushResult sendPush(PushPayload payload) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(jpushConfig.getMasterSecret(), jpushConfig.getAppKey(), null, clientConfig);
        try {
            return jpushClient.sendPush(payload);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
        }
        return null;
    }

    /**
     * 生成极光推送对象PushPayload（采用java SDK）
     *
     * @param alias
     * @param alert
     * @return PushPayload
     */
    private PushPayload buildPushObject_android_ios_alias_alert(String alias, String alert, String key, String value) {
        Map<String, String> extraParams = new HashMap<>(2);
        extraParams.put(key, value);
        return buildPushObject_android_ios_alias_alert(alias, alert, null, extraParams);
    }

    /**
     * 生成极光推送对象PushPayload（采用java SDK）
     *
     * @param alias
     * @param alert
     * @return PushPayload
     */
    private PushPayload buildPushObject_android_ios_alias_alert(String alias, String alert, Map<String, String> extraParams) {
        return buildPushObject_android_ios_alias_alert(alias, alert, null, extraParams);
    }


    /**
     * 生成极光推送对象PushPayload（采用java SDK）
     *
     * @param alias 对象目标
     * @param alert 内容
     * @param title 标题
     * @param extraParams 额外参数
     * @return PushPayload
     */
    private PushPayload buildPushObject_android_ios_alias_alert(String alias, String alert, String title, Map<String, String> extraParams) {
        String intentJsonStr = "{\"url\":\"intent:#Intent;action=com.zoweunion.mechlion.utils.push;component=com.zoweunion.mechlion/com.zoweunion.mechlion.utils.push.OpenClickActivity;end\"}";
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(intentJsonStr, JsonObject.class);

        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(alert)
                                .setTitle(title)
                                .setAlertType(1)
                                .setIntent(jsonObject)
                                .addExtras(extraParams)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(IosAlert.newBuilder()
                                        .setTitleAndBody(title, "", alert)
                                        .build())
                                        .setSound("default")
                                .addExtras(extraParams)
                                .build())
                        .build())
//                .setMessage(Message.content("----------test----------"))//
                .setOptions(Options.newBuilder()
                        .setApnsProduction(jpushConfig.getApnsProduction())//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
    }



    /**
     * 生成极光推送对象PushPayload（采用java SDK）
     *
     * @param title
     * @param alert
     * @param key
     * @param value
     * @return PushPayload
     */
    private PushPayload buildPushObject_android_ios_all_alert(String alert, String title, String key, String value) {
        Map<String, String> extraParams = new HashMap<>(2);
        extraParams.put(key, value);
        return buildPushObject_android_ios_alias_alert( alert, title, extraParams);
    }

    /**
     * 构建推送给所有android和ios用户参数载荷
     * @param alert
     * @param title
     * @param extraParams
     * @return
     */
    private PushPayload buildPushObject_android_ios_all_alert(String alert, String title, Map<String, String> extraParams) {
        JPushClient jpushClient = new JPushClient(jpushConfig.getMasterSecret(), jpushConfig.getAppKey());

        String intentJsonStr = "{\"url\":\"intent:#Intent;action=com.zoweunion.mechlion.utils.push;component=com.zoweunion.mechlion/com.zoweunion.mechlion.utils.push.OpenClickActivity;end\"}";
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(intentJsonStr, JsonObject.class);

        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setTitle(title)
                                .setAlert(alert)
                                .setAlertType(1)
                                .setIntent(jsonObject)
                                .addExtras(extraParams)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(IosAlert.newBuilder()
                                        .setTitleAndBody(title, "", alert)
                                        .build())
                                        .setSound("default")
                                .addExtras(extraParams)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        //true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setApnsProduction(jpushConfig.getApnsProduction())
                        //消息在JPush服务器的失效时间（测试使用参数）
                        .setTimeToLive(90)
                        .build())
                .build();
    }

    /**
     * 极光推送>>ios
     *
     * @param params
     */
    public void jpushIOS(Map<String, String> params) {
        //创建JPushClient
        JPushClient jpushClient = new JPushClient(jpushConfig.getMasterSecret(), jpushConfig.getAppKey());
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.ios())//ios平台的用户
                .setAudience(Audience.all())//所有用户
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(params.get("msg"))
                                .setBadge(+1)
                                //这里是设置提示音(更多可以去官网看看)
                                .setSound("default")
                                .addExtras(params)
                                .build())
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(false).build())
                .setMessage(Message.newBuilder().setMsgContent(params.get("msg")).addExtras(params).build())//自定义信息
                .build();
        try {

            PushResult pu = jpushClient.sendPush(payload);

        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

}